// import { loginPassword } from '@/api';
// import { useCookies } from '@vueuse/integrations/useCookies';
import { defineStore } from 'pinia';
import { Storage } from '@/utils/Storage';
import { AUTH_TOKEN_KEY } from '@/enums/cacheEnum';
import { login, logout } from '@/api/user';

// const { VITE_TOKEN_KEY } = import.meta.env;
// const token = useCookies().get(VITE_TOKEN_KEY as string);

interface StoreUser {
  token: string;
  info: Partial<API.UserInfo>;
}

export const useUserStore = defineStore({
  id: 'app-user',
  state: (): StoreUser => ({
    token: Storage.get(AUTH_TOKEN_KEY, null),
    info: {},
  }),
  getters: {
    getToken(): string {
      return this.token;
    },
    getUserInfo(): any {
      return this.info || {};
    },
  },
  actions: {
    setInfo(info: any) {
      this.info = info ? info : '';
    },
    /** 清空token及用户信息 */
    resetToken() {
      this.token = '';
      this.info = {};
      Storage.clear();
    },
    /** 登录成功保存token */
    setToken(token: string) {
      this.token = token ?? '';
      const ex = 7 * 24 * 60 * 60 * 1000;
      Storage.set(AUTH_TOKEN_KEY, this.token, ex);
    },
    /** 登录 */
    async login(params: API.LoginParams) {
      try {
        const res = await login(params);
        if (res) {
          const data = res.data;
          this.setToken(data?.token);
          this.setInfo(data?.info);
          return res;
        }
        return false;
      } catch (error) {
        return Promise.reject(error);
      }
    },
    /** 登出 */
    async logout() {
      const res = await logout();
      this.resetToken();
      // resetRouter();
      return res;
    },
  },
  // persist: {
  //   key: AUTH_TOKEN_KEY,
  //   storage: localStorage,
  //   paths: [AUTH_TOKEN_KEY],
  // },
  // persist: {
  //   key: 'token',
  //   storage: localStorage,
  //   paths: ['token'],
  // },
});
